package com.lagou.sale.dao;

import com.lagou.sale.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class JedisDao {

    @Autowired
    private JedisPool jedisPool;
    private String script = "if redis.call('EXISTS',KEYS[1]) and tonumber(redis.call('get',KEYS[1])) > 0 " +
            "then redis.call('decr',KEYS[1]); return 0; else return 1; end";


    public int getStockByItemNum(int itemNum) {
        try (Jedis jedis = jedisPool.getResource()) {
            String num = jedis.get(Constant.ItemStock + itemNum);
            if (num == null || "".equals(num)) {
                throw new RuntimeException(String.format("this item: %s not found", itemNum));
            } else {
                return Integer.parseInt(num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public boolean reduceStock(int itemNum) {
        try (Jedis jedis = jedisPool.getResource()) {
            Long eval = (Long) jedis.eval(script, 1, Constant.ItemStock + itemNum);
            return eval == 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void addStock(int itemNum) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.incr(Constant.ItemStock + itemNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
